package cn.weichuyu.snippet.comparejar.util;

import org.apache.log4j.Logger;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.MessageDigest;

public class FileUtils {
    private static char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

    static Logger logger = Logger.getLogger(FileUtils.class);

    public static String getMd5ByFile(String absolutePath) {
        String value = null;
        try {
            File f = new File(absolutePath);
            InputStream in = new FileInputStream(f);
            byte[] buffer = new byte[1024];
            int len = 0;
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            while ((len = in.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
            }
            bos.close();
            byte[] getData = bos.toByteArray();
            value = getMd5ByFile(getData);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return value;
    }

    public static String getMd5ByFile(byte[] bytes) {
        String value = null;
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(bytes);
            byte[] byteArray = md5.digest();
            char[] charArray = new char[byteArray.length * 2];
            int index = 0;
            for (byte b : byteArray) {
                charArray[index++] = hexDigits[b >>> 4 & 0xf];
                charArray[index++] = hexDigits[b & 0xf];
            }
            value = new String(charArray);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return value;
    }
}
